/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package domein;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Lucas
 */
public class Client
{
    private String server;
    private int poort;
    private String username;
    private Socket socket;
    private ObjectInputStream input;
    private ObjectOutputStream output;

    public Client(String server, int poort, String username)
    {
        this.server = server;
        this.poort = poort;
        this.username = username;

        start();
    }

    public void start()
    {
        try {
            try {
                socket = new Socket(server, poort);
            }
            catch (UnknownHostException ex) {
                Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
            }
            catch (IOException ex) {
                Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
            }
            writeOutput("Connection accepted on " + socket.getInetAddress().toString());

            input = new ObjectInputStream(socket.getInputStream());
            output = new ObjectOutputStream(socket.getOutputStream());



            new Listener().start();


            output.writeObject(username);

        }
        catch (IOException ex) {
            Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
            disconnect();
        }
    }

    public void disconnect()
    {
        try {
            output.close();
            input.close();
            socket.close();
        }
        catch (IOException ex) {
            Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void sendMessage(String msg)
    {
        try {
            output.writeObject(msg);
        }
        catch (IOException ex) {
            Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    public synchronized void writeOutput(String message)
    {
        System.out.println(message);
    }

    class Listener extends Thread
    {
        public void run()
        {
            while (true) {
                try {
                    String msg = (String) input.readObject();

                    writeOutput(msg);
                }
                catch (IOException ex) {
                    Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
                }
                catch (ClassNotFoundException ex) {
                    Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }
}
